﻿using KingRoad.EPM.CompletionMaterialsEntity.Model;
using KingRoad.EPM.Web.Areas.CompletionMaterials.CompletionMaterialsFramework.Common;
using KingRoad.EPM.Web.Areas.CompletionMaterials.ViewModels;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace KingRoad.EPM.Web.Areas.CompletionMaterials.Controllers
{
    /// <summary>
    /// 文件材料表管理
    /// </summary>
    public class VolumeListController : BaseController
    {
        public ActionResult Index(string type, string id)
        {
            BcdVolumeDirectoryViewModel vm = new BcdVolumeDirectoryViewModel();
            ViewBag.Type = type;
            //第几页
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            ViewBag.Pft_ID = id;
            //案卷目录表
            string sql = " Pft_ID='" + id + "' ";
            int totalRecord = 0;
            //当前页码
            vm.TheBcdVolumedirectoryList = BcdVolumedirectoryUIRule.GetEntityListByContionRe(ViewBag.pageNum, ViewBag.numPerPage, "Vd_State,Vd_Order", out totalRecord, sql, "asc", "View_VolumeList");
            vm.TheBcdVolumedirectoryList.ForEach(t =>
            {
                t.FilePath = FilePath(t.Vd_ID, t.Pft_ID);
                t.FileCount = GetFilesCount(Server.MapPath(String.Format("~/Files/{0}", t.FilePath)), 0);
            });
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return PartialView(vm);
        }

        /// <summary>
        /// 未归档文件列表分页
        /// </summary>
        /// <returns></returns>
        public ActionResult SplitPage()
        {
            BcdVolumeDirectoryViewModel vm = new BcdVolumeDirectoryViewModel();
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            ViewBag.Type = Request.Form["Type"];
            ViewBag.Pft_ID = Request.Form["Pft_ID"];
            if (ViewBag.pageNum == 0 || ViewBag.numPerPage == 0)
                return Index(ViewBag.Type, ViewBag.FId);
            else
            {
                //工程项目与归档类型与案卷目录对应关系表
                string sql = " Pft_ID='" + ViewBag.Pft_ID + "' ";
                ViewBag.iput_code = Request.Form["iput_code"];
                ViewBag.iput_name = Request.Form["iput_name"];
                if (ViewBag.iput_code != "")
                    sql += " and Vd_Code like '%" + ViewBag.iput_code + "%' ";
                if (ViewBag.iput_name != "")
                    sql += " and Vd_Name like '%" + ViewBag.iput_name + "%' ";
                //案卷目录表
                vm.TheBcdVolumedirectoryList = BcdVolumedirectoryUIRule.GetEntityListByContionRe(ViewBag.pageNum, ViewBag.numPerPage, "Vd_State,Vd_Order", out totalRecord, sql, "asc", "View_VolumeList");
                vm.TheBcdVolumedirectoryList.ForEach(t =>
                {
                    t.FilePath = FilePath(t.Vd_ID, t.Pft_ID);
                    t.FileCount = GetFilesCount(Server.MapPath(String.Format("~/Files/{0}", t.FilePath)), 0);
                });
                //总条数
                ViewBag.totalcount = totalRecord;
                //总页数
                ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            }
            return View("Index", vm);
        }


        #region 未归档文件增删改查
        /// <summary>
        /// 添加未归档文件
        /// </summary>
        /// <returns></returns>
        public ActionResult Add(string Pft_ID)
        {
            BcdVolumeDirectoryViewModel vm = new BcdVolumeDirectoryViewModel();
            //卷内目录信息Volumedirectory
            vm.TheBcdVolumedirectoryInfo = new BcdVolumedirectoryInfo();
            vm.TheBcdVolumedirectoryInfo.Vd_ID = Guid.NewGuid().ToString().ToUpper();
            vm.TheBcdVolumedirectoryInfo.Pft_ID = Pft_ID;
            vm.TheBcdVolumedirectoryInfo.Vd_Duty = BcdProfiletypeUIRule.GetEntityById(new Guid(Pft_ID)).Pft_Unit;
            //附件
            ViewBag.FilePath = FilePath(vm.TheBcdVolumedirectoryInfo.Vd_ID, vm.TheBcdVolumedirectoryInfo.Pft_ID);
            return View(vm);
        }
        /// <summary>
        /// 添加未归档文件提交
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AddPost(BcdVolumeDirectoryViewModel vm)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                //添加  卷内目录表
                //操作人ID及名称
                vm.TheBcdVolumedirectoryInfo.Vd_OperateUserID = GetLoginUserId;
                vm.TheBcdVolumedirectoryInfo.Vd_OperateUserName = GetLoginUserRealName;
                vm.TheBcdVolumedirectoryInfo.Vd_OperateTime = DateTime.Now;
                BcdVolumedirectoryUIRule.InsertEntity(vm.TheBcdVolumedirectoryInfo);
            });
            //附件 继续添加时使用
            string vdid = Guid.NewGuid().ToString().ToUpper();
            ViewBag.FilePath = FilePath(vdid, vm.TheBcdVolumedirectoryInfo.Pft_ID);
            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "添加成功",
                    type = "check",
                    navTabId = "",
                    id = vm.TheBcdVolumedirectoryInfo.Pft_ID,
                    name = GetNodeName(vm.TheBcdVolumedirectoryInfo.Pft_ID),
                    vd_id = vdid,
                    path = ViewBag.FilePath,
                    rel = "",
                    callbackType = "",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "添加失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }

        /// <summary>
        /// 修改未归档文件
        /// </summary>
        /// <returns></returns>
        public ActionResult Edit(string id)
        {
            BcdVolumeDirectoryViewModel vm = new BcdVolumeDirectoryViewModel();
            //卷内目录信息Volumedirectory
            vm.TheBcdVolumedirectoryInfo = BcdVolumedirectoryUIRule.GetEntityById(new Guid(id));
            //附件
            ViewBag.FilePath = FilePath(vm.TheBcdVolumedirectoryInfo.Vd_ID, vm.TheBcdVolumedirectoryInfo.Pft_ID);
            return View(vm);
        }
        /// <summary>
        /// 修改未归档文件提交
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult EditPost(BcdVolumeDirectoryViewModel vm)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                //修改  未归档文件
                vm.TheBcdVolumedirectoryInfo.Vd_OperateUserID = GetLoginUserId;              //操作人ID及名称 添加权限时赋值
                vm.TheBcdVolumedirectoryInfo.Vd_OperateUserName = GetLoginUserRealName;
                vm.TheBcdVolumedirectoryInfo.Vd_OperateTime = DateTime.Now;
                BcdVolumedirectoryUIRule.UpdateEntity(vm.TheBcdVolumedirectoryInfo);
            });

            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "修改成功",
                    type = "edit",
                    navTabId = "",
                    id = vm.TheBcdVolumedirectoryInfo.Fl_ID,
                    rel = "",
                    callbackType = "",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "修改失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 查看未归档文件
        /// </summary>
        /// <returns></returns>
        public ActionResult Detail(string id)
        {
            BcdVolumeDirectoryViewModel vm = new BcdVolumeDirectoryViewModel();
            //卷内目录信息Volumedirectory
            vm.TheBcdVolumedirectoryInfo = BcdVolumedirectoryUIRule.GetEntityById(new Guid(id));

            //附件
            ViewBag.FilePath = FilePath(vm.TheBcdVolumedirectoryInfo.Vd_ID, vm.TheBcdVolumedirectoryInfo.Pft_ID);
            vm.TheBcdVolumedirectoryInfo.FileCount = GetFilesCount(Server.MapPath(String.Format("~/Files/{0}", ViewBag.FilePath)), 0);
            return View(vm);
        }
        /// <summary>
        /// 删除未归档文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult Del(string id)
        {
            string pftId = "";
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                BcdVolumedirectoryInfo info= BcdVolumedirectoryUIRule.GetEntityById(new Guid(id));
                pftId = info.Pft_ID;
                if (info.Fl_ID != null)
                {
                    //如果已关联案卷
                    BcdFilelistInfo finfo = BcdFilelistUIRule.GetEntityById(new Guid(info.Fl_ID));
                    //修改  案卷操作人信息
                    finfo.Fl_OperateUserID = GetLoginUserId;              //操作人ID及名称
                    finfo.Fl_OperateUserName = GetLoginUserRealName;
                    finfo.Fl_OperateTime = DateTime.Now;
                    BcdFilelistUIRule.UpdateEntity(finfo);
                }
                BcdVolumedirectoryUIRule.DeleteEntity(id);
            });

            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "删除成功",
                    type = "check",
                    navTabId = "",
                    id = pftId,
                    name = GetNodeName(pftId),
                    rel = "",
                    callbackType = "",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "删除失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 审核未归档文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult Check(string id)
        {
            BcdVolumedirectoryInfo info = BcdVolumedirectoryUIRule.GetEntityById(new Guid(id));
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                info.Vd_State = 1;
                info.Vd_CMan = GetLoginUserRealName;
                info.Vd_CTime = DateTime.Now;
                BcdVolumedirectoryUIRule.CheckObject(info);
            });

            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "审核成功",
                    type = "check",
                    navTabId = "",
                    id = info.Pft_ID,
                    name = GetNodeName(info.Pft_ID),
                    rel = "",
                    callbackType = "",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "审核失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        #endregion

        #region 组卷
        /// <summary>
        /// 组卷
        /// </summary>
        /// <returns></returns>
        public ActionResult FileCreat(string type, string pftId)
        {
            ViewBag.Type = type;
            ViewBag.pftId = pftId;
            BcdVolumeDirectoryViewModel vm = new BcdVolumeDirectoryViewModel();
            //案卷目录表
            BcdFilelistInfo info = new BcdFilelistInfo();
            BcdProfiletypeInfo pInfo = BcdProfiletypeUIRule.GetEntityById(new Guid(pftId));
            info.Fl_ID = Guid.NewGuid().ToString().ToUpper();
            info.Pft_ID = pftId;
            info.Fl_FileType = GetFileParTypeName(pInfo.Pft_PIds, pInfo.Fd_Name);
            info.Fl_Code = pInfo.Fd_Code;

            string sql = " Fl_Code='" + info.Fl_Code + "' ";
            if (info.Fl_Code.IndexOf(".") >= 0)
            {
                sql = " Fl_Code like '" + GetFileCode(info.Fl_Code) + "%' ";
            }
            int count = BcdFilelistUIRule.GetNumbBySql(sql);
            if (count == 0)
            {
                List<BcdFilelistInfo> flList = BcdFilelistUIRule.GetEntityListBySql(sql);
                count = flList.Count;
            }
            //自增长
            info.Fl_Numb = count + 1;
            info.Fl_Item = pInfo.P_Name;
            info.Fl_Unit = pInfo.Pft_Unit;
            info.Fl_Kept = pInfo.Fd_Kept;
            vm.TheBcdFilelistInfo = info;
            return View(vm);
        }
        /// <summary>
        /// 未归档文件选择列表
        /// </summary>
        /// <param name="pftId"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult FileCheckList(string pftId, string fileIds)
        {
            ViewBag.fileIds = fileIds;
            BcdVolumeDirectoryViewModel vm = new BcdVolumeDirectoryViewModel();
            ViewBag.pftId = pftId;
            //第几页
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 10;
            if (pftId != null && pftId != "null" && pftId != "")
            {
                //案卷目录表
                string sql = " Fl_ID is null and Vd_State=1 and Pft_ID='" + pftId + "' ";
                int totalRecord = 0;
                //当前页码
                vm.TheBcdVolumedirectoryList = BcdVolumedirectoryUIRule.GetEntityListByContionRe(ViewBag.pageNum, ViewBag.numPerPage, "Vd_Order", out totalRecord, sql, "asc", "View_VolumeList");
                //总条数
                ViewBag.totalcount = totalRecord;
                //总页数
                ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            }
            else
            {
                vm.TheBcdVolumedirectoryList = new List<BcdVolumedirectoryInfo>();
            }
            return PartialView(vm);
        }
        /// <summary>
        /// 未归档文件选择列表分页
        /// </summary>
        /// <returns></returns>
        public ActionResult FileCheckListSplitPage()
        {
            ViewBag.pftId = Request.Form["pftId"];
            ViewBag.fileIds = Request.Form["fileIds"];
            BcdVolumeDirectoryViewModel vm = new BcdVolumeDirectoryViewModel();
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            if (ViewBag.pageNum == 0 || ViewBag.numPerPage == 0)
                return FileCheckList(ViewBag.pftId, ViewBag.fileIds);
            else
            {
                //工程项目与归档类型与案卷目录对应关系表
                string sql = " Fl_ID is null and Vd_State=1 and Pft_ID='" + ViewBag.pftId + "' ";
                ViewBag.iput_ch_code = Request.Form["iput_ch_code"];
                ViewBag.iput_ch_name = Request.Form["iput_ch_name"];
                if (ViewBag.iput_ch_code != "")
                    sql += " and Vd_Code like '%" + ViewBag.iput_ch_code + "%' ";
                if (ViewBag.iput_ch_name != "")
                    sql += " and Vd_Name like '%" + ViewBag.iput_ch_name + "%' ";
                //案卷目录表
                vm.TheBcdVolumedirectoryList = BcdVolumedirectoryUIRule.GetEntityListByContionRe(ViewBag.pageNum, ViewBag.numPerPage, "Vd_Order", out totalRecord, sql, "asc", "View_VolumeList");
                //总条数
                ViewBag.totalcount = totalRecord;
                //总页数
                ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            }
            return View("FileCheckList", vm);
        }

        /// <summary>
        /// 组卷提交
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult FileCreatPost(BcdVolumeDirectoryViewModel vm)
        {
            bool codeState = true;
            BcdProjectfileInfo pInfo = new BcdProjectfileInfo();
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                if (GetFileCodeCount(vm.TheBcdFilelistInfo.Fl_Code, vm.TheBcdFilelistInfo.Fl_Numb) == 0)
                {
                    //添加  案卷目录表
                    vm.TheBcdFilelistInfo.Fl_OperateUserID = GetLoginUserId;              //操作人ID及名称
                    vm.TheBcdFilelistInfo.Fl_OperateUserName = GetLoginUserRealName;
                    vm.TheBcdFilelistInfo.Fl_OperateTime = DateTime.Now;
                    BcdFilelistUIRule.InsertEntity(vm.TheBcdFilelistInfo);

                    foreach (BcdVolumedirectoryInfo info in vm.TheBcdVolumedirectoryList)
                    {
                        BcdVolumedirectoryInfo vInfo = BcdVolumedirectoryUIRule.GetEntityById(new Guid(info.Vd_ID));
                        vInfo.Vd_State = 2;
                        vInfo.Fl_ID = vm.TheBcdFilelistInfo.Fl_ID;
                        vInfo.Vd_Order = info.Vd_Order;
                        vInfo.Vd_Code = info.Vd_Code;
                        vInfo.Vd_Name = info.Vd_Name;
                        vInfo.Vd_Page = info.Vd_Page;

                        vInfo.Vd_OperateTime = DateTime.Now;
                        vInfo.Vd_OperateUserID = GetLoginUserId;
                        vInfo.Vd_OperateUserName = GetLoginUserName;
                        BcdVolumedirectoryUIRule.UpdateEntity(vInfo);
                    }
                }
                else
                {
                    codeState = false;
                }
            });

            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                if (codeState)
                {
                    jsonReturn = new
                    {
                        statusCode = "200",
                        message = "组卷成功",
                        type = "check",
                        navTabId = "",
                        id = vm.TheBcdFilelistInfo.Pft_ID,
                        name = GetNodeName(vm.TheBcdFilelistInfo.Pft_ID),
                        rel = "",
                        callbackType = "",
                        forwardUrl = "",
                        confirmMsg = ""
                    };
                }
                else
                {
                    jsonReturn = new
                    {
                        statusCode = "300",
                        message = "档案号已存在，请更换！",
                    };
                }
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "组卷失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        #endregion
    }
}
